package com.afeng.web.module.common.utils;

import com.afeng.web.common.cache.GuavaCacheUtils;
import com.afeng.web.common.util.SessionUtil;
import com.afeng.web.framework.core.constant.Constants;
import com.afeng.web.framework.exception.AdminException;
import com.afeng.web.module.admin.model.Menu;
import com.afeng.web.module.admin.model.User;

import java.util.List;
import java.util.Set;

/**
 * 数据库角色主键为1是管理员
 */
@SuppressWarnings("unchecked")
public class AdminUtils {

    private static final String SysUserPermissionCacheKey = "sys-perm:admin:";//后台用户权限缓存KEY前缀

    public static User getSysUser() {
        User user = (User) SessionUtil.getSessionObject(Constants.CURRENT_USER);
        if (user == null) {
            throw AdminException.toAccessDenied("系统用户不存在");
        }
        return user;
    }

    //判断用户是否拥有某个权限
    public static boolean isPermitted(String permission) {
        if (getSysUser().isAdmin()) {
            return true;
        }
        Set<String> permSet = getSysUserPermissionCache();
        if (permSet != null && permSet.size() > 0) {
            return permSet.contains(permission);
        }
        return false;
    }

    //判断用户是否拥有某个角色
    public static boolean hasRole(String role) {
        //TODO 未实现
        return true;
    }

    /**
     * 保存用户权限缓存
     *
     * @param menus 菜单列表
     */
    public static void setSysUserPermissionCache(List<Menu> menus) {
        if (menus != null && menus.size() > 0) {
            String cacheKey = SysUserPermissionCacheKey + getSysUser().getUserId();
            GuavaCacheUtils.put(cacheKey, menus);
        }
    }

    /**
     * 获取用户权限缓存
     */
    public static Set<String> getSysUserPermissionCache() {
        String cacheKey = SysUserPermissionCacheKey + getSysUser().getUserId();
        Object value = GuavaCacheUtils.get(cacheKey);
        if (value != null) {
            return (Set<String>) value;
        }
        return null;
    }

    //清除权限缓存
    public static void cleanSysUserPermissionCache() {
        String cacheKey = SysUserPermissionCacheKey + getSysUser().getUserId();
        GuavaCacheUtils.del(cacheKey);
    }

}
